const state = {
  dbResources: [],
  // selected: []
  selected: JSON.parse(window.localStorage.getItem("selected-resources")) || []
}

const mutations = {
  addSelectedRes(state, item) {
    state.selected.push(item)
    resSetResourceSelected(state)
    window.localStorage.setItem("selected-resources", JSON.stringify(state.selected))
  },

  incrementSelectedRes(state, item) {
    for (var i = 0; i < state.selected.length; i++) {
      if (state.selected[i].resourceNo === item.resourceNo) {
        state.selected.splice(i, 1)
        resSetResourceSelected(state)
        window.localStorage.setItem("selected-resources", JSON.stringify(state.selected))
      }
    }
  },

  clearAllSelectedRes(state) {
    state.selected = []
    resSetResourceSelected(state)
    window.localStorage.setItem("selected-resources", JSON.stringify(state.selected))
  },

  initDbResources(state, item) {
    state.dbResources = []
    item.resList.forEach(el => {
      el['selected'] = false
      if (state.selected.length > 0 && item.importRes) {
        getResourceSelected(el)
      }
      state.dbResources.push(el)
    })
  }
}

function resSetResourceSelected(state) {
  state.dbResources.forEach(el => {
    el['selected'] = false
    getResourceSelected(el)
  })
}

function getResourceSelected(item) {
  state.selected.forEach(sl => {
    if (sl.resourceNo === item.resourceNo) {
      item['selected'] = true
    }
  })
}

export default {
  namespaced: true,
  state,
  mutations
}
